package com.ruoyi.plus.web.service;

import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.enums.UserStatus;
import com.ruoyi.common.exception.base.BaseException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.web.service.UserDetailsServiceImpl;
import com.ruoyi.system.service.ISysUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

@Slf4j
@Service
@Primary
public class UserDetailsServiceImplPlus extends UserDetailsServiceImpl {

    @Autowired
    private ISysUserService userService;

    public UserDetails loadUserByPhone(String phone) throws UsernameNotFoundException
    {
        SysUser user = null;
        if (StringUtils.isNumeric(phone)) {
            user = userService.selectUserByPhoneNumber(phone);
        }
        if (StringUtils.isNull(user)){
            //通过手机号查询不到时,通过用户名查询,如可查询到也可登录.
            user = userService.selectUserByUserName(phone);
        }
        if (StringUtils.isNull(user))
        {
            log.info("登录手机号：{} 不存在.", phone);
            throw new UsernameNotFoundException("登录手机号：" + phone + " 不存在");
        }
        else if (UserStatus.DELETED.getCode().equals(user.getDelFlag()))
        {
            log.info("登录手机号：{} 已被删除.", phone);
            throw new BaseException("对不起，您的账号：" + phone + " 已被删除");
        }
        else if (UserStatus.DISABLE.getCode().equals(user.getStatus()))
        {
            log.info("登录手机号：{} 已被停用.", phone);
            throw new BaseException("对不起，您的账号：" + phone + " 已停用");
        }

        return createLoginUser(user);
    }
}
